package com.squirrel.michale;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 使用完整框架代码推荐使用jdk 17（和平台版本保持一致）；
 * 框架解析输入输出已引入 fastjson(1.2.83)；24年Q3起正式认证中使用（模拟自测场景已于23Q4使用）
 *
 * @author 命题组
 * @since 2023-1-1
 */
class Solution {
    char[] commonChars(int count, List<String> strings) {
        List<Map<Character, Integer>> totalMap = new ArrayList<>();
        for (String single : strings) {
            char[] charArray = single.toCharArray();
            Map<Character, Integer> charFrequencMap = new HashMap<>();
            for (char c : charArray) {
                charFrequencMap.put(c, charFrequencMap.get(c) + 1);
            }
            charFrequencMap.entrySet().removeIf(entry -> entry.getValue() < count);
            totalMap.add(charFrequencMap);
        }

        Set<Character> result = totalMap.get(0).keySet();
        for (int i = 1; i < totalMap.size(); i++) {
            Set<Character> characters1 = totalMap.get(i).keySet();
            Iterator<Character> iterator = result.iterator();
            while (iterator.hasNext()) {
                Character next = iterator.next();
                if (!characters1.contains(next)) {
                    iterator.remove();
                }
            }

        }

        if (result.isEmpty()) {
            return new char[]{};
        }else{
            List<Character> characterList = new ArrayList<>(result);
            Collections.sort(characterList);
            Character[] array = characterList.toArray(new Character[0]);
            char[] real = new char[]{};
            for (int i = 0; i < array.length; i++) {
                real[i] = array[i];
            }
            return real;

        }
    }
}